<template>
    <div class="page-wrap" v-loading="loading">
        <div style="padding: 0px 24px 12px 12px; background: #fff">
            <a-page-header @back="handleBack">
                <template #title> 注册制项目：{{ detailData.projectName }}</template>
            </a-page-header>
            <div class="margin-t-16">
                <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                    <a-row>
                        <a-col :span="24">
                            <a-form-item label="PBI目录">
                                <span>
                                    {{ pbiName }}
                                </span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="项目目标">
                                <div v-html="detailData.projectObjective"></div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="主线版本" name="verMgtId">
                                <flexbox justify="space-between">
                                    <flexbox>
                                        <span v-if="disabled">
                                            {{ detailData?.pmpVersionManagementDTO?.versionNumber }}
                                        </span>
                                        <a-select style="width: 200px" allowClear v-model:value="form.verMgtId" v-else>
                                            <a-select-option :key="item.id" v-for="item of versionOptions">
                                                {{ item.versionNumber }}
                                            </a-select-option>
                                        </a-select>
                                        <div class="warning-color cursor-pointer margin-l-8" @click="handleCreateVersion" v-if="!disabled">
                                            新增版本
                                        </div>
                                    </flexbox>

                                    <a-button type="primary" :loading="saveLoading" @click="handleSave" v-if="!disabled">保存</a-button>
                                </flexbox>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </div>
        <div style="background: #fff">
            <MainContent :lubiaoDetail="detailData" v-if="detailData.id && detailData?.pmpVersionManagementDTO?.versionNumber" />
        </div>
        <CreateVersionModal :lubiaoDetail="detailData" ref="CreateVersionModalRef" @success="getVersionOptions" />
    </div>
</template>

<script lang="ts">
import MainContent from './MainContent/index.vue';
import CreateVersionModal from './components/CreateVersionModal.vue';
import api from '@/api';
import store from '@/store';
import { treeFilter } from '@/utils/tree';
import { transformDataByFlatProperty } from '@/utils/tree';
import { deepClone } from '@/utils/util';
import { message } from 'ant-design-vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { defineComponent, ref, unref, reactive, toRefs, computed } from 'vue';
export default defineComponent({
    components: {
        CreateVersionModal,
        MainContent
    },
    setup() {
        const ruleFormRef = ref<any>();
        const CreateVersionModalRef = ref<any>();
        const state = reactive<any>({
            loading: false,
            detailData: {},
            pbiName: '',
            pbiTreeData: [],
            form: {
                verMgtId: ''
            },
            versionOptions: [],
            disabled: true,
            saveLoading: false
        });
        const { handleBack, route } = useRouterApi({
            backQuery: {
                path: '/energyManage/analysisReport'
            }
        });
        const rules = computed(() => {
            const rules = {
                verMgtId: [{ required: true, message: '主线版本不能为空', trigger: 'change', type: 'number' }]
            };
            return state.disabled ? {} : rules;
        });
        const getDetailData = async () => {
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.registeredProjectModel.findById(query);
            if (success) {
                state.detailData = { ...moule };
                state.form.verMgtId = state.detailData.verMgtId;
            } else {
                message.error(errorMsg);
            }
            return success;
        };
        const getVersionOptions = async () => {
            const query = {
                type: 1,
                catalogCode: state.detailData.catalogCode
            };
            const { success, moule } = await api.versionControlModel.findByCatalogCode(query);
            if (success) {
                state.versionOptions = [...moule];
            }
        };
        // 获取所有pbi数据
        const getPbiTreeData = async () => {
            const query = {
                type: 2
            };
            const { success, moule } = await api.portalControlModel.getSystemProductCatalogTreeData(query);
            if (success) {
                if (moule) {
                    state.pbiTreeData = transformDataByFlatProperty(deepClone(JSON.parse(moule)));
                    const target = treeFilter(state.pbiTreeData, (node) => node.catalogCode === state.detailData.catalogCode);
                    state.pbiName = getPbiName(target, '');
                }
            }
        };
        const getPbiName = (target, name) => {
            if (target && target.length) {
                if (name) {
                    name = `${name} / ${target[0].catalogName}`;
                } else {
                    name = target[0].catalogName;
                }
                return getPbiName(target[0].subNodes, name);
            }
            return name;
        };
        const handleCreateVersion = () => {
            unref(CreateVersionModalRef).open();
        };
        const handleSave = async () => {
            state.saveLoading = true;
            const res = await unref(ruleFormRef).validate();
            if (!res) {
                state.saveLoading = false;
                return;
            }
            const query = {
                ...state.detailData,
                ...state.form
            };
            const { success, errorMsg } = await api.registeredProjectModel.save(query);
            if (success) {
                getDetailData();
                message.success('保存成功');
            } else {
                message.error(errorMsg);
            }
            state.saveLoading = false;
        };
        const checkDisabled = async () => {
            // 找出该系统默认的当前处理人
            const { success, moule } = await api.systemManagerModel.findManagersBySystem({
                catalogCode: state.detailData.catalogCode,
                position: '产品经理'
            });
            if (success) {
                const target = moule.find((item) => item.empId === store.getters.userInfo.employeeDTO.empId);
                state.disabled = target ? false : true;
            }
        };
        const init = async () => {
            state.loading = true;
            state.detailData = {};
            await getDetailData();
            checkDisabled();
            getPbiTreeData();
            getVersionOptions();
            state.loading = false;
        };
        init();
        return {
            ruleFormRef,
            CreateVersionModalRef,
            rules,
            ...toRefs(state),
            handleBack,
            handleCreateVersion,
            getVersionOptions,
            handleSave
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    height: 100%;
    .handleBtn-cont {
        ::v-deep(.ant-btn) {
            &:hover {
                z-index: 10000 !important;
            }
        }
    }
}
</style>